/**
 * 用户模块Store
 */
import { defineStore } from 'pinia';
import { computed, ref } from 'vue';

// 创建Store
export const globalStore = defineStore(
  'global_ceduoduo',
  () => {
    // 用户信息
    let userInfo = ref({});
    let openid = ref('');
    let token = ref('');
    let videoInfo = ref({});
    let alipayInfo = ref({});
    let wepayInfo = ref({});
    let cardInfo = ref({});
    let isBindMobile = ref(false);
    let safeAreaBottom = ref(0);
    safeAreaBottom = computed(() => {
      return uni.$u.sys().safeAreaInsets.bottom;
    });
    const getUrlParam = (name) => {
      var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)'); // 构造一个含有目标参数的正则表达式对象
      var r = window.location.search.substr(1).match(reg); // 匹配目标参数
      if (r != null) return unescape(r[2]);
      return null; // 返回参数值
    };
    let getUserInfo = () => {
      uni.$request
        .service({
          url: '/wx/user/info',
          method: 'POST',
          data: {
            openid: openid.value,
          },
        })
        .then((res) => {
          userInfo.value = res;
        });
    };
    const getToken = (openid) => {
      return new Promise((resolve, reject) => {
        uni.$request
          .service({
            url: '/wx/token',
            method: 'POST',
            data: { openid },
            isToast: true,
          })
          .then((res) => {
            token.value = res.token;
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      });
    };
    return {
      openid,
      token,
      userInfo,
      alipayInfo,
      wepayInfo,
      cardInfo,
      isBindMobile,
      safeAreaBottom,
      getToken,
      getUrlParam,
      getUserInfo,
      videoInfo,
    };
  },
  {
    // 重要：模块必须开启持久化，才会持久化！！！
    // 注意：默认持久化，只在H5端有效，因为默认使用的是localStorage，小程序端不能使用这个API，所以需要重写存取方法，转调给UniApp的持久化方法
    // persist: true,
    persist: {
      // 默认值，就是使用localStorage
      // storage: localStorage
      // 重写存取方法，转调给UniApp
      storage: {
        getItem(key) {
          return uni.getStorageSync(key);
        },
        setItem(key, val) {
          uni.setStorageSync(key, val);
        },
      },
    },
  },
);
